<template>
  <page-header-wrapper :title="false">
    <a-card title="订单详情">
      <a-descriptions bordered title="" size="small">
        <a-descriptions-item label="调出店面" :span="3"> {{ info?.outStoreName }} </a-descriptions-item>
        <a-descriptions-item label="接收店面" :span="3"> {{ info?.inStoreName }} </a-descriptions-item>
        <a-descriptions-item label="日期" :span="3"> {{ info?.outDate }} </a-descriptions-item>
        <a-descriptions-item label="调出人" :span="3"> {{ info?.operatorName }} </a-descriptions-item>
        <a-descriptions-item label="接收日期" :span="3"> {{ info?.inDate }} </a-descriptions-item>
        <a-descriptions-item label="接收人" :span="3"> {{ info?.checkName }} </a-descriptions-item>
        <a-descriptions-item label="属性" :span="3"> {{ info?.attribute }} </a-descriptions-item>
        <a-descriptions-item label="调库类型" :span="3"> {{ info?.adType }} </a-descriptions-item>
        <a-descriptions-item label="数量" :span="3"> {{ info?.commNum }} </a-descriptions-item>
        <a-descriptions-item label="成本" :span="3"> {{ info?.amount }} </a-descriptions-item>
        <a-descriptions-item label="备注" :span="3"> {{ info?.memo }} </a-descriptions-item>
        <a-descriptions-item label="状态" :span="3">   {{ info?.checkStatus === '1' ? '已审核' : '未审核' }} </a-descriptions-item> 
        <a-descriptions-item label="审核人" :span="3" v-if="info?.checkStatus == '1'"> {{ info.checkName }} </a-descriptions-item>
        <a-descriptions-item label="操作" :span="3">
          <div style="display: flex">
            <a-button type="primary" style="margin: 0px 5px" @click="handleEdit(info)" v-if="info?.checkStatus === '0'">编辑</a-button>
            <a-button type="danger" style="margin-right: 5px" v-if="info?.checkStatus === '0'" @click="handleBack()">撤销</a-button>
            <a-button type="primary" style="margin: 0px 5px" v-if="info?.checkStatus === '0'" @click="handleCheckPur()">审核</a-button>
            <a-button type="success" v-if="info?.checkStatus === '1'" style="margin: 0px 5px" @click="handleUnCheckPur()">反审核</a-button>
            
            <a-button style="margin: 0px 5px" v-print="printOption">打印调库单(汇总)</a-button>
            <a-button style="margin: 0px 5px" v-print="printOption">打印调库单(详情)</a-button>
          </div>
        </a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card title="调货记录详情" style="margin-top: 24px">
      <template #extra>
        <a-tooltip>
          <template #title> 数据导出</template>
          <a-button type="primary" icon="database" @click="handleExpert(queryParam)"></a-button>
        </a-tooltip>
      </template>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="8">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.keyword" placeholder="请输入筛选" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="handleSearch(queryParam)" :loading="searchLoading">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" @click="handleAddGoods(info)" v-if="info?.checkStatus === '0'">修改商品列表</a-button>
      </div>

      <a-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :loading="searchLoading"
        :data-source="loadData"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428bca" @click="handleGoodsDetail(record)">详情</a-tag>
            <!-- <a-tag color="#428bca" v-if="info?.checkStatus === '0'" @click="handleGoodsEdit(record)">编辑</a-tag>
            <a-popconfirm title="是否确认删除？" @confirm="handleGoodsDelete(record)">
              <a-tag color="#428bca" v-if="info?.checkStatus === '0'">删除</a-tag>
            </a-popconfirm> -->
          </template>
        </span>
      </a-table>
    </a-card>
    <a-card title="操作记录" style="margin-top: 24px">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="8">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.keyword" placeholder="请输入筛选" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="handleRecordSearch(queryParam)" :loading="recordLoading">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- <div class="table-operator">
        <a-button icon="cloud-upload">导出</a-button>
      </div> -->

      <a-table
        ref="recordtable"
        size="default"
        rowKey="key"
        :columns="recordcolumns"
        :loading="recordLoading"
        :data-source="recordloadData"
        :pagination="recordPagination"
        @change="handleRecordTableChange"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template> {{ record.empName }} <a-tag color="#428bca" @click="handleUserDetail(record)">详情</a-tag> </template>
        </span>
      </a-table>
    </a-card>
    <div style="width: 0; height: 0; overflow: hidden">
      <div id="printMe" class="objectDialogFlowPrint">
        <div class="myPrint">
          <detailList :list="this.loadData" :info="this.info"/>
        </div>
      </div>
    </div>
    <price-form
      ref="priceModal"
      :visible="priceVisible"
      :loading="priceLoading"
      :model="priceMdll"
      @cancel="handlePriceCancel"
      @ok="handlePriceOk"
    />
    <edit-form
      ref="editModal"
      :visible="editVisible"
      :loading="editLoading"
      :model="editMdll"
      @cancel="handleEditCancel"
      @ok="handleEditOk"
    />
  </page-header-wrapper>
</template>

<script>
import PriceForm from './PriceForm'
import EditForm from './EditForm'
import {
  pendingAdjustUsingGET,
  pendingAdjustListUsingGET,
  updateAdjustUsingPOST,
  stCounterReceiveUsingPOST,
  stCounterRevokeUsingPOST,
  stCounterRejectUsingPOST,
  exportAdjustDetailListUsingPOST
} from '@/api/api/diaoku.ts'
import { getOperRecordListUsingPOST } from '@/api/api/caigouguanli.ts'
import detailList from './../components/detail'
export default {
  name: 'CounterShiftRecordDetail',
  components: {
    PriceForm,
    EditForm, 
    detailList,
  },
  data() {
    return {
      printOption: {
        id: 'printMe', // 打印元素的id 不需要携带#号
        // preview: true, // 开启打印预览
        previewTitle: '打印预览', // 打印预览标题
        popTitle: '入库详情 - 达臻贸易', // 页眉标题 默认浏览器标题 空字符串时显示undefined 使用html语言
      },
      info: {},
      advanced: false,
      priceMdll: null,
      editMdll: null,
      priceVisible: false,
      editVisible: false,
      priceLoading: false,
      editLoading: false,
      searchLoading: false,
      recordLoading: false,
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        status: '',
      },
      queryParam1: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        status: '',
      },
      pagination: {},
      columns: [
        {
          title: '商品名',
          dataIndex: 'goodsName',
        },
        {
          title: '串码1',
          dataIndex: 'phoneCode1',
        },
        {
          title: '串码2',
          dataIndex: 'phoneCode2',
        },
        {
          title: '金额(元)',
          dataIndex: 'adAmount',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      loadData: [],
      recordcolumns: [
        {
          title: '时间',
          dataIndex: 'operTime',
        },
        {
          title: '类型',
          dataIndex: 'action',
        },
        {
          title: '操作',
          dataIndex: 'option',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      recordloadData: [],
      recordPagination: {},
    }
  },
  mounted() {
    this.getDetail()
    this.handleSearch(this.queryParam)
    this.handleRecordSearch(this.queryParam1)
  },
  methods: {
    handleExpert(params){
      exportAdjustDetailListUsingPOST({ ...params, orderId: this.$route.params.id }).then((res) => {
          const blob = new Blob([res], {
            type: 'application/vnd.ms-excel;charset=utf-8',
          })
          const filename = '调货记录详情列表' + '.xlsx'
          // 将blob对象转为一个URL
          var blobURL = window.URL.createObjectURL(blob)
          // 创建一个a标签
          var tempLink = document.createElement('a')
          // 隐藏a标签
          tempLink.style.display = 'none'
          // 设置a标签的href属性为blob对象转化的URL
          tempLink.href = blobURL
          // 给a标签添加下载属性
          tempLink.setAttribute('download', filename)
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 将a标签添加到body当中
          document.body.appendChild(tempLink)
          // 启动下载
          tempLink.click()
          // 下载完毕删除a标签
          document.body.removeChild(tempLink)
          window.URL.revokeObjectURL(blobURL)
          this.$message.success('导出成功~')
        })  
    },
    handleAddGoods() {
      this.$router.push({ path: `/shift/shopShiftRecord/edit/${this.$route.params.id}`,query:{storeId:this.$route.query.storeId} })
    },
    getDetail() {
      pendingAdjustUsingGET({ id: this.$route.params.id })
        .then((res) => {
          this.info = res.data
        })
        .catch(() => {
          this.$message.error('获取详情失败,请联系管理员')
        })
    },
    handleSearch(params) {
      this.searchLoading = true
      pendingAdjustListUsingGET({ ...params, orderId: this.$route.params.id })
        .then((res) => {
          this.searchLoading = false
          this.loadData = res.data.list
        this.queryParam.pageNo = this.pagination.current
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch((error) => {
          this.searchLoading = false
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination)
      const pager = { ...this.pagination }
      pager.current = pagination.current
 pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition:this.queryParam.queryCondition,
        status:this.queryParam.status,
        date:this.queryParam.date
      })
    },
    handleRecordSearch(params) {
      this.recordLoading = true
      getOperRecordListUsingPOST({ ...params, orderId: this.$route.params.id })
        .then((res) => {
          this.recordloadData = res.data.list
          this.recordLoading = false
          this.recordPagination = { ...this.recordPagination, total: Number(res.data.total) }
        })
        .catch((error) => {
          this.recordLoading = false
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleRecordTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
 pager.pageSize = pagination.pageSize
      this.recordPagination = pager
      this.handleRecordSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition: '',
        status: '',
      })
    },
    handleEdit(record) {
      this.editMdll = record
      this.editVisible = true
    },
    handleEditOk() {
      const form = this.$refs.editModal.form
      this.editLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          // 修改 e.g.
          updateAdjustUsingPOST({ ...values  })
            .then(() => {
              this.getDetail()
              this.$message.success('操作成功')
              this.editVisible = false
              this.editLoading = false
              // 重置表单数据
              form.resetFields()
            })
            .catch((error) => {
              this.confirmLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        } else {
          this.editLoading = false
        }
      })
    },
    handleEditCancel() {
      this.editVisible = false
      const form = this.$refs.editModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleGoodsEdit(record) {
      this.priceMdll = record
      this.priceVisible = true
    },
    handlePriceOk() {
      const form = this.$refs.priceModal.form
      this.priceLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          // 修改 e.g.
          updateAdjustUsingPOST({ ...values  })
            .then(() => {
              this.handleSearch(this.queryParam)
              this.$message.success('操作成功')
              this.priceVisible = false
              this.priceLoading = false
              // 重置表单数据
              form.resetFields()
            })
            .catch((error) => {
              this.confirmLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        } else {
          this.priceLoading = false
        }
      })
    },
    handlePriceCancel() {
      this.priceVisible = false
      const form = this.$refs.priceModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleChange() {
      this.$router.push({ path: `/purchasing/ProtectPriceRecord/edit/1` })
    },
    handleGoodsDetail(record) {
      this.$router.push({ path: `/goods/name/${record.id}` })
    },
    handleUserDetail(record) {
      this.$router.push({ path: `/user/user/${record.operator}` })
    },
    handleAddBack() {
      this.$router.push({ path: `/purchasing/backstorerecord/add/${this.$route.params.id}` })
    },
    handleGoodsDelete(record) {
      var that = this
      deletePurDetailUsingPOST({ id: record?.id })
        .then(() => {
          that.handleSearch(this.queryParam)
          that.$message.success('操作成功')
        })
        .catch((error) => {
          that.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },

    handleCheckPur() {
      const that = this
      that.$confirm({
        title: '审核通过',
        content: '你确定要审核通过该订单吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          stCounterReceiveUsingPOST({ id: that.$route.params.id })
        .then(() => {
          that.handleSearch(that.queryParam)
          that.getDetail()
          that.$message.success('操作成功')
        })
        .catch((error) => {
          that.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
        },
      })
    },
    handleUnCheckPur() {
      const that = this
      that.$confirm({
        title: '反审核',
        content: '你确定要反审核该订单吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          stCounterRevokeUsingPOST({ id: that.$route.params.id })
        .then(() => {
          that.handleSearch(that.queryParam)
          that.getDetail()
          that.$message.success('操作成功')
        })
        .catch((error) => {
          that.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
        },
      })
    },
    handleBack() {
      const that = this
      that.$confirm({
        title: '撤销订单',
        content: '你确定要撤销该订单吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          stCounterRejectUsingPOST({ id: that.$route.params.id })
        .then(() => {
          that.$router.back()
          that.$message.success('操作成功')
        })
        .catch((error) => {
          that.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
        },
      })
    },
  },
}
</script>
